package org.deng.vertx.core;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpServer;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Libin.Deng
 * @date 2021/8/22 18:44
 * @desc
 */
@Slf4j
public class MyFirstVerticle extends AbstractVerticle {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public void start() throws Exception {
        //每个 Verticle 在部署的时候都会被分配一个 Context,context上执行的操作总是 在同一个 Event Loop 线程中
        Context context = vertx.getOrCreateContext();
        if (context.isEventLoopContext()) {
            System.out.println("Context attached to Event Loop");
        } else if (context.isWorkerContext()) {
            System.out.println("Context attached to Worker Thread");
        } else if (! Context.isOnVertxThread()) {
            System.out.println("Context not attached to a thread managed by vert.x");
        }
        //获取配置
        String configName = config().getString("name");
        log.info("configName:{}", configName);
        HttpServer httpServer = vertx.createHttpServer();
        httpServer.requestHandler(req -> {
            log.info("当前线程");
            req.response()
                    .putHeader("content-type", "text/plain")
                    .end("Hello World!");
        }).listen(8080);
        logger.info("{},{},{}启动成功，8080端口", this, vertx, httpServer);
        //事件总线
        eventBusDemo();
    }

    /**
     * 每一个 Vert.x 实例都有一个单独的 Event Bus 实例。您可以通过 Vertx 实例的
     * eventBus
     *  方法来获得对应的 EventBus 实例。
     */
    private void eventBusDemo(){
        EventBus eb = vertx.eventBus();
        //接收消息
        eb.consumer("news.uk.sport", message -> {
            System.out.println("I have received a message: " + message.body());
            message.reply("收到");
        });

        //发布消息 Vert.x会按照发送者发送消息的顺序，将消息以同样的顺序传递给处理器。
        DeliveryOptions options = new DeliveryOptions();
        //设置消息头
        options.addHeader("some-header", "some-value");
        //设置超时事件 ms 默认 30 * 1000 (30秒)
        options.setSendTimeout(20);
        eb.publish("news.uk.sport", "Yay! Someone kicked a ball", options);
        eb.request("news.uk.sport", "你好", options, rep->{
            if(rep.succeeded()){
                Object body = rep.result().body();
                System.out.println("收到回复:"+body.toString());
            }
        });



    }
}
